#include "pagepasswordset.h"
#include "ui_pagepasswordset.h"

PagePasswordSet::PagePasswordSet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PagePasswordSet)
{
    ui->setupUi(this);
    setAutoFillBackground(true);  //设置自动填充
    QPalette palette = BKGCLR;
    setPalette(palette);

    m_pNumKeyBoard = new NumberKeyBoard(this);
    m_pNumKeyBoard->move(720,230);
    connect(m_pNumKeyBoard,SIGNAL(setNumber(int)),this,SLOT(slotNumber(int)));
    connect(m_pNumKeyBoard,SIGNAL(cancel()),this,SLOT(slotClear()));
    connect(m_pNumKeyBoard,SIGNAL(backspace()),this,SLOT(slotBackspace()));
    connect(m_pNumKeyBoard,SIGNAL(ack()),this,SLOT(slotOK()));

    inputlist.append(ui->lineEdit_OldPwd);
    inputlist.append(ui->lineEdit_NewPwd);
    for(int i=0; i<inputlist.size(); ++i)
        inputlist.at(i)->installEventFilter(this);
}

PagePasswordSet::~PagePasswordSet()
{
    delete ui;
}

void PagePasswordSet::on_Btn_Return_clicked()
{
    emit returnToMaintMenu();
}

void PagePasswordSet::setPageActive(bool xActive)
{
    ui->Btn_Confirm->setEnabled(xActive);
}

bool PagePasswordSet::eventFilter(QObject *obj, QEvent *event)
{
    for(int i=0; i<inputlist.size(); ++i)
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            if(obj == inputlist.at(i))
            {
                inputlist.at(i)->setStyleSheet("background-color: rgb(100,255,255); border: 1px solid white;font:20px 'Arial';");
                m_pFocusLinedit = inputlist.at(i);
            }
            else
                inputlist.at(i)->setStyleSheet("background-color: white; border: 1px solid white;font:20px 'Arial';");
        }
    }
    return QWidget::eventFilter(obj, event);
}

void PagePasswordSet::slotBackspace()
{
    if(m_pFocusLinedit != NULL)
        m_pFocusLinedit->setText(m_pFocusLinedit->text().left(m_pFocusLinedit->text().size()-1));
}


void PagePasswordSet::slotNumber(int i)
{
    if(m_pFocusLinedit != NULL)
        m_pFocusLinedit->setText(m_pFocusLinedit->text() + QString().setNum(i));
}

void PagePasswordSet::slotClear()
{
    if(m_pFocusLinedit != NULL)
        m_pFocusLinedit->setText("");
}

void PagePasswordSet::slotOK()
{
    on_Btn_Confirm_clicked();
}

void PagePasswordSet::on_Btn_Confirm_clicked()
{
    if(ui->lineEdit_OldPwd->text() == GlobalConfig::password)
    {
        if(ui->lineEdit_NewPwd->text().isEmpty())
            ui->Error_Label->setText("新密码不能为空");
        else
        {
            ui->Error_Label->setText("新密码设置成功");
            GlobalConfig::writePasswd(ui->lineEdit_NewPwd->text());
            ui->lineEdit_OldPwd->setText("");
            ui->lineEdit_NewPwd->setText("");
        }
    }
    else
    {
        ui->Error_Label->setText("旧密码不正确");
    }
    if(m_xErrorTimerBusy)
        return;
    m_xErrorTimerBusy = true;
    QTimer::singleShot(3000,this,[=](){
        ui->Error_Label->setText("");
        m_xErrorTimerBusy = false;
    });
}
